<?PHP

ini_set("display_standard_errors","0");
ini_set("display_errors","1");

if ($_SERVER['SCRIPT_NAME'] == '/~phillipv/ava-player-database/dbca/login.php')
{
    Authentication::requireHttps();
}
else
{
    Authentication::requireHttpsAndAuthentication();
}

function connect()
{
	global $db;
	$db = mysqli_connect('localhost', 'phillipv_user1', 'pas', 'phillipv_AVA') or die(mysqli_error($db));
}

class Authentication
{
    private static $isSessionStarted = false;

    // Standard site password hashed with SHA512
    private static $authorizedUser = 'phillipv';
    private static $hashedPass =
        '1cad00636836eb98e0333ea5097197f0c12f4ee3fc82e0ae6792a60eacf2bc0fb86994ddda5921bdee9238dc10358ee34f8c513c363ee512e9f0ac16e096dba1';

    private static function initializeSession()
    {
        if ( !Authentication::$isSessionStarted )
        {
            session_start();
            Authentication::$isSessionStarted = true;
        }
    }

    public static function requireHttps()
    {
        if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on')
        {
            Authentication::redirectToLogin();
        }
    }

    public static function requireHttpsAndAuthentication()
    {
        if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' || !Authentication::isAuthenticated() )
        {
            Authentication::redirectToLogin();
        }
    }

    public static function redirectToLogin()
    {
        header('Location: https://'.$_SERVER['HTTP_HOST'].'/~phillipv/ava-player-database/dbca/login.php');
        exit();
    }

    public static function isAuthenticated()
    {
        Authentication::initializeSession();
        return isset($_SESSION['ava_admin_authorized']) && $_SESSION['ava_admin_authorized'] == 1;
    }

    public static function Authenticate($user,$pass)
    {
        if ( $user != Authentication::$authorizedUser )
            return false;

        if ( hash('sha512',$pass) != Authentication::$hashedPass )
            return false;

        Authentication::initializeSession();
        $_SESSION['ava_admin_authorized'] = 1;
        return true;
    }

    public static function unAuthenticate()
    {
        Authentication::initializeSession();
        unset($_SESSION['ava_admin_authorized']);
        Authentication::redirectToLogin();
    }
}
	
?>